package org.dromara.school.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.dromara.common.core.exception.ExcelException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.school.domain.Campus;
import org.dromara.school.domain.Discipline;
import org.dromara.school.domain.Teacher;
import org.dromara.school.domain.bo.TeacherBo;
import org.dromara.school.domain.vo.TeacherVo;
import org.dromara.school.service.ICampusService;
import org.dromara.school.service.IDisciplineService;
import org.dromara.school.service.ITeacherService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description //TODO
 * @Date 2025/6/16 15:53
 * @Author 郭建波
 **/
public class TeacherImportExcelListener  extends AnalysisEventListener<TeacherVo> {

    private ITeacherService teacherService;
    private ICampusService schoolCampusService;
    private IDisciplineService disciplineService;


    //定义存放数据的集合
    private List<TeacherVo> list = new ArrayList<>();

    public TeacherImportExcelListener(ITeacherService teacherService, ICampusService schoolCampusService,IDisciplineService disciplineService) {
        this.teacherService = teacherService;
        this.schoolCampusService = schoolCampusService;
        this.disciplineService = disciplineService;
    }

    // 一行行读取内容
    @Override
    public void invoke(TeacherVo teacherVo, AnalysisContext analysisContext) {
        TeacherVo getTeacherDto = this.checkNull(teacherVo, analysisContext);
        //读取每行数据，对数据进行判断以及处理
        List<Long> schoolCampusIds = getTeacherDto.getSchoolCampusId();
        //根据教师姓名，教师手机号查看是否已经存在
        this.checkHasTeacher(teacherVo,analysisContext);
        TeacherVo teacher = new TeacherVo();
        BeanUtils.copyProperties(teacherVo,teacher);
        teacher.setSchoolCampusId(schoolCampusIds);
        //根据导入的校区 学科名称来判断学科是否存在
        //主学科验证
        Long mainDisciplineId = this.checkMainDiscipline(teacher, analysisContext).get(0).getDisciplineId();
        teacher.setMainDisciplineId(mainDisciplineId);
        list.add(teacher);
    }




    private List<Discipline> checkMainDiscipline(TeacherVo teacherVo, AnalysisContext context) {

        List<Discipline> listDisciplineIds = new ArrayList<>();

        String mainDiscipline = teacherVo.getMainDiscipline();

        List<Long> schoolCampusId = teacherVo.getSchoolCampusId();
        for(Long campusId : schoolCampusId){
            Discipline discipline = new Discipline();
            discipline.setSubjectName(mainDiscipline);
            discipline.setSchoolCampusId(Long.valueOf(campusId));
            Discipline getDiscipline = this.disciplineService.findDiscipline(discipline);
            //验证 如果多个校区返回的都是null 那么说明没有这个学科
            if(getDiscipline!=null){
                listDisciplineIds.add(getDiscipline);
            }
            //如果多个校区返回的都是null 抛出异常
        }
        if(listDisciplineIds.size() == 0){
            int row = context.readRowHolder().getRowIndex() + 1;
            throw new ExcelException(context.readSheetHolder().getSheetName() + "：第" + row + "行 " + "学科:" + mainDiscipline + " 不存在，请先你创建该学科！");
        }
        return listDisciplineIds;

    }


    private void checkHasTeacher(TeacherVo teacherVo, AnalysisContext context) {

        TeacherVo selectTeacher = new TeacherVo();
        selectTeacher.setTeacherName(teacherVo.getTeacherName());
        selectTeacher.setTelphone(teacherVo.getTelphone());
        Teacher teacher = this.teacherService.selectTeacher(selectTeacher);
        if(teacher!=null){
            int row = context.readRowHolder().getRowIndex() + 1;
            throw new ExcelException(context.readSheetHolder().getSheetName() + "：第" + row + "行 " + "教师:" + teacherVo.getTeacherName() + " 已经存在该老师信息，请检查！");
        }

    }


    // 读取表头内容
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
    }

    // 读取完成之后的操作
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        list.forEach(teacher -> {
            TeacherBo teacherBo = new TeacherBo();
            teacherBo.setMainDisciplineId(teacher.getMainDisciplineId());
            teacherBo.setSchoolCampusId(teacher.getSchoolCampusId());
            teacherBo.setTeacherName(teacher.getTeacherName());
            teacherBo.setSex(teacher.getSex().equals("男")?0L:1L);
            teacherBo.setNation(teacher.getNation());
            teacherBo.setTelphone(teacher.getTelphone());
            teacherBo.setPosition(teacher.getPosition());
            teacherBo.setJoinDate(teacher.getJoinDate());
            teacherBo.setOnDutyStatus(teacher.getOnDutyStatus().equals("是")?"Y":"N");
            teacherBo.setOnJobStatus(teacher.getOnJobStatus().equals("是")?"Y":"N");
            teacherBo.setProvince(teacher.getProvince());
            teacherBo.setCity(teacher.getCity());
            teacherBo.setDistricts(teacher.getDistricts());
            this.teacherService.insertByBo(teacherBo);


        });


    }


    //判断每一行必填数据，返回校区id
    public TeacherVo checkNull(TeacherVo teacherVo, AnalysisContext context) {
        List<Long> listcampusId = new ArrayList<>();
        int row = context.readRowHolder().getRowIndex() + 1;
        if(StringUtils.isEmpty(teacherVo.getBandingSchools())||
            StringUtils.isEmpty(teacherVo.getTeacherName())||
            StringUtils.isEmpty(teacherVo.getTelphone())||
            StringUtils.isEmpty(teacherVo.getMainDiscipline())){
            throw new ExcelException(context.readSheetHolder().getSheetName() + "：第" + row + "行  出现导入必须要的数据为空,请检查！");
        }

        List<String> listSchools = Arrays.stream(teacherVo.getBandingSchools().split("\\|")).collect(Collectors.toList());
        for(String sname:listSchools){
            Campus schoolCampus = new Campus();
            schoolCampus.setCampusName(sname);
            Campus getSchoolCampus = schoolCampusService.findSchoolCampus(schoolCampus);
            if (StringUtils.isNull(getSchoolCampus)) {
                throw new ExcelException(context.readSheetHolder().getSheetName() + "：第" + row + "行  导入的校区没有找到,请检查！");
            }
            listcampusId.add(getSchoolCampus.getCampusId());
        }
        teacherVo.setSchoolCampusId(listcampusId);

        return teacherVo;
    }



}
